package com.ruoyi.livedemo.service;

import com.ruoyi.livedemo.dto.PagedResult;
import com.ruoyi.livedemo.dto.ReminderRequest;
import com.ruoyi.livedemo.entity.Reminder;
import com.ruoyi.livedemo.mapper.ReminderMapper;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
public class ReminderService {

    private final ReminderMapper reminderMapper;

    public PagedResult<Reminder> list(Long userId, int page, int size) {
        int pageSize = size <= 0 ? 10 : size;
        int currentPage = Math.max(page, 0);
        int offset = currentPage * pageSize;
        List<Reminder> items = reminderMapper.findPage(userId, offset, pageSize);
        long total = reminderMapper.countByUser(userId);
        return new PagedResult<>(total, items);
    }

    @Transactional
    public Reminder create(Long userId, ReminderRequest request) {
        Reminder reminder = new Reminder();
        reminder.setUserId(userId);
        reminder.setTitle(request.getTitle());
        reminder.setMessage(request.getMessage());
        reminder.setRemindAt(request.getRemindAt());
        reminder.setPriority(request.getPriority());
        reminder.setCategory(request.getCategory());
        reminder.setAcknowledged(Boolean.TRUE.equals(request.getAcknowledged()));
        reminder.setCoverPath(request.getCoverPath());
        reminderMapper.insert(reminder);
        return reminder;
    }

    @Transactional
    public Reminder update(Long userId, Long id, ReminderRequest request) {
        Reminder reminder = reminderMapper.findByIdAndUser(id, userId);
        if (reminder == null) {
            throw new IllegalArgumentException("未找到提醒");
        }
        reminder.setTitle(request.getTitle());
        reminder.setMessage(request.getMessage());
        reminder.setRemindAt(request.getRemindAt());
        reminder.setPriority(request.getPriority());
        reminder.setCategory(request.getCategory());
        reminder.setAcknowledged(request.getAcknowledged());
        reminder.setCoverPath(request.getCoverPath());
        reminderMapper.update(reminder);
        return reminder;
    }

    @Transactional
    public void acknowledge(Long userId, Long id) {
        Reminder reminder = reminderMapper.findByIdAndUser(id, userId);
        if (reminder == null) {
            throw new IllegalArgumentException("未找到提醒");
        }
        reminder.setAcknowledged(true);
        reminderMapper.update(reminder);
    }

    @Transactional
    public void delete(Long userId, Long id) {
        reminderMapper.delete(id, userId);
    }
}

